import { director, log } from 'cc';
import { js } from 'cc';
import { CocosTools } from '../../utils/CocosTools';

declare const CC_EDITOR;

/**
 * 可全局查找类型对象，方便浏览器的console命令进行交互命令
 * 在有实例化之后，全局的instances下就有对应类名的查找器，调用就可返回实例
 * 目前应用于BaseView和BaseManager
 * 这样调用：
 * instances.HC90S7``
 * 对于Manager也可以使用对应system的名字
 * instances.game_system``
 */
export class GlobalInstanceFinder {

    componentRegister() {
        if (CC_EDITOR) return;
        globalThis.instances = globalThis.instances ?? {};
        let className = js.getClassName(this);
        globalThis.instances[className] = () => {
            let coms = director.getScene().getComponentsInChildren(className);
            coms.forEach((_, idx) =>
                log(`%c${className}, [${idx}], ${CocosTools.path(_.node)}`, 'font-weight:bold;background-color:gray;color:white;')
            );
            if (coms.length == 0) return null;
            else if (coms.length == 1) return coms[0];
            return coms;
        };
    }

    systemRegister(id: string) {
        if (CC_EDITOR) return;
        globalThis.instances = globalThis.instances ?? {};
        let className = js.getClassName(this);
        let func = () => {
            let system = director.getSystem(id);
            log(`%c${className}, ${system.id}`, 'font-weight:bold;background-color:black;color:white;')
            return system;
        };
        globalThis.instances[className] = func;
        globalThis.instances[id] = func;
    }

}